'use strict';
const Service = require('egg').Service;

class paymentService extends Service {
  async getPaymentList(params) {
    const ctx = this.ctx;
    const { offset, pageSize, paymentTimeStart, paymentTimeEnd, phoneNo, nickName } = params;
    const body = {
      totalCount: 0,
      list: [],
    };
    const commonSql = `
    from file 
    left join user on user.id = file.create_id
    where file.status = 2
    ${paymentTimeStart ? `and file.payment_time >= '${paymentTimeStart}'` : ''}
    ${paymentTimeEnd ? `and file.payment_time < '${paymentTimeEnd}'` : ''}
    ${phoneNo ? `and user.phone_no = ${phoneNo}` : ''}
    ${nickName ? `and user.nick_name like '%${nickName}%'` : ''}`;
    const totalSql = `
      SELECT count(*) AS total
      ${commonSql}
    `;
    const totalModel = await ctx.model.query(totalSql, { type: 'SELECT' });
    body.totalCount = totalModel && totalModel[0].total;
    if (body.totalCount === 0) {
      return await ctx.service.returnBody.index(body, '获取付款列表失败！');
    }
    const Sql = `select
    user.nick_name as nickName,
    user.phone_no as phoneNo,
    file.batch_no as batchNo,
    file.file_name as fileName,
    file.file_url as fileUrl,
    DATE_FORMAT( file.payment_time,'%Y-%m-%d %H:%i:%s') as paymentTime
    ${commonSql}
    order by file.created_time desc
    ${pageSize ? `limit ${offset}, ${pageSize}` : ''}
    `;
    const Model = await ctx.model.query(Sql, { type: 'SELECT' });
    if (Model) {
      body.list = Model;
    }
    return await ctx.service.returnBody.index(body, '获取付款列表失败！');
  }
  async paymentOrRejection(params) {
    const ctx = this.ctx;
    const { fileId, batchNo, status, message } = params;
    if (!fileId && !batchNo) {
      return await ctx.service.returnBody.index(null, '请检查参数！');
    }
    const now = new Date();
    const updateParams = {
      status,
      message,
      updatedTime: now,
    };
    const where = {};
    if (fileId) {
      where.id = fileId;
    }
    if (batchNo) {
      where.batchNo = batchNo;
    }
    if (status === 2) {
      updateParams.paymentTime = now;
    }
    const model = await ctx.model.File.update(updateParams, {
      where,
    });
    return await ctx.service.returnBody.index(model ? {} : null, '操作失败！');
  }
}

module.exports = paymentService;
